<template>
  <div class="order-detail-container">
    <div class="page-header">
      <h2 class="page-title">订单详情</h2>
      <div>
        <el-button @click="goBack">返回</el-button>
        <el-button v-if="canEdit" type="primary" @click="goToEdit">编辑</el-button>
        <!--        <el-dropdown v-if="order.id" split-button type="primary" @click="printOrder" @command="handleCommand">-->
        <!--          打印订单-->
        <!--          <template #dropdown>-->
        <!--            <el-dropdown-menu>-->
        <!--              <el-dropdown-item command="export">导出PDF</el-dropdown-item>-->
        <!--              <el-dropdown-item command="email">发送邮件</el-dropdown-item>-->
        <!--            </el-dropdown-menu>-->
        <!--          </template>-->
        <!--        </el-dropdown>-->
      </div>
    </div>

    <el-card v-loading="loading" class="detail-card">
      <template v-if="!loading && order.id">
        <el-descriptions :column="2" border title="基本信息">
          <el-descriptions-item label="订单编号">{{ order.orderNumber }}</el-descriptions-item>
          <el-descriptions-item label="订单日期">{{ formatDate(order.purchaseDate) }}</el-descriptions-item>
          <el-descriptions-item label="供应商名称">{{ order.supplierName }}</el-descriptions-item>
          <el-descriptions-item label="采购员">{{ order.purchaser || '-' }}</el-descriptions-item>
          <el-descriptions-item label="预计交付日期">{{ formatDate(order.expectedDeliveryDate) }}</el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ formatDateTime(order.createTime) }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="getStatusType(order.status)">{{ order.status }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="订单金额">{{ formatCurrency(order.totalAmount) }}</el-descriptions-item>
          <el-descriptions-item :span="2" label="备注">{{ order.remark || '无' }}</el-descriptions-item>
        </el-descriptions>

        <div class="section-title">
          <span class="title-text">商品明细</span>
          <span class="goods-count">共 {{ order.items?.length || 0 }} 种商品</span>
        </div>
        <el-table
            :data="order.items || []"
            :header-cell-style="{background:'#f5f7fa', color: '#606266', fontWeight: 'bold'}"
            border
            stripe
            style="width: 100%; margin-bottom: 20px; border-radius: 4px; overflow: hidden;"
        >
          <el-table-column align="center" label="序号" type="index" width="60"></el-table-column>
          <el-table-column label="商品名称" min-width="180" prop="itemName" show-overflow-tooltip></el-table-column>
          <el-table-column label="规格型号" min-width="150" prop="specification"
                           show-overflow-tooltip></el-table-column>
          <el-table-column align="center" label="单位" prop="unit" width="80"></el-table-column>
          <el-table-column align="center" label="数量" prop="quantity" width="100"></el-table-column>
          <el-table-column align="right" label="单价" width="120">
            <template #default="{ row }">
              {{ formatCurrency(row.unitPrice) }}
            </template>
          </el-table-column>
          <el-table-column align="right" label="金额" width="120">
            <template #default="{ row }">
              <span class="amount-text">{{ formatCurrency(row.total) }}</span>
            </template>
          </el-table-column>
        </el-table>

        <div class="amount-summary">
          <span class="label">订单总金额：</span>
          <span class="value">{{ formatCurrency(order.totalAmount) }}</span>
        </div>

        <div class="section-title">关联单据</div>
        <div v-if="relatedDocuments.length > 0" class="related-docs">
          <el-descriptions :column="2" border>
            <el-descriptions-item v-for="(doc, index) in relatedDocuments" :key="index" :label="doc.type">
              <el-link type="primary" @click="viewRelatedDoc(doc)">{{ doc.number }}</el-link>
              <el-tag :type="doc.status === '已完成' ? 'success' : 'warning'" size="small" style="margin-left: 8px">
                {{ doc.status }}
              </el-tag>
            </el-descriptions-item>
          </el-descriptions>
        </div>
        <el-empty v-else description="暂无关联单据"></el-empty>
      </template>

      <el-empty v-else-if="!loading" description="未找到订单信息"></el-empty>
    </el-card>
  </div>
</template>

<script lang="ts" setup>
import {computed, onMounted, reactive, ref} from 'vue';
import {useRoute, useRouter} from 'vue-router';
import {ElMessage} from 'element-plus';
import {getOrderDetail, getOrderRelatedDocuments} from '@/api/order.ts';

// 路由
const router = useRouter();
const route = useRoute();
const loading = ref(false);
const orderId = computed(() => route.params.id ? Number(route.params.id) : null);

// 订单信息 - 修改属性名与后端对应
const order = reactive<any>({
  id: undefined,
  orderNumber: '',
  supplierName: '',
  purchaseDate: '',
  expectedDeliveryDate: '',
  purchaser: '',
  status: '',
  totalAmount: 0,
  remark: '',
  createTime: '',
  updateTime: '',
  items: []
});

// 关联单据类型定义
interface RelatedDocument {
  type: string;
  number: string;
  status: string;
  url: string;
}

// 关联单据
const relatedDocuments = ref<RelatedDocument[]>([]);

// 是否可以编辑
const canEdit = computed(() => {
  return ['待处理', '处理中'].includes(order.status);
});

// 页面加载
onMounted(() => {
  if (orderId.value) {
    fetchOrderData(orderId.value.toString());
  }
});

// 获取订单详情
const fetchOrderData = async (id: string) => {
  loading.value = true;
  try {
    const response = await getOrderDetail(id);

    // 填充数据
    if (response.data) {
      Object.assign(order, response.data);

      // 获取关联单据
      await fetchRelatedDocuments(id);
    } else {
      ElMessage.error('获取订单详情失败，未返回有效数据');
      router.push('/dashboard/order-list');
    }
  } catch (error) {
    console.error('订单详情获取失败:', error);
    ElMessage.error('订单详情获取失败，请重试');
  } finally {
    loading.value = false;
  }
};

// 获取关联单据
const fetchRelatedDocuments = async (orderId: string) => {
  try {
    const response = await getOrderRelatedDocuments(orderId);
    if (response.code === 200 && response.data) {
      const {receipts, invoices} = response.data;
      relatedDocuments.value = [
        ...receipts.map((doc: any) => ({
          type: doc.type,
          number: doc.number,
          status: doc.status,
          url: doc.url
        })),
        ...invoices.map((doc: any) => ({
          type: doc.type,
          number: doc.number,
          status: doc.status,
          url: doc.url
        }))
      ];
    }
  } catch (error) {
    console.error('获取关联单据失败:', error);
    relatedDocuments.value = [];
  }
};

// 返回列表页
const goBack = () => {
  router.push('/dashboard/order-list');
};

// 跳转到编辑页
const goToEdit = () => {
  if (orderId.value) {
    router.push(`/dashboard/order-edit/${orderId.value}`);
  }
};

// // 打印订单
// const printOrder = () => {
//   ElMessage.success('开始打印订单');
//   // 实际打印逻辑
// };
//
// // 处理下拉命令
// const handleCommand = (command: string) => {
//   switch (command) {
//     case 'export':
//       ElMessage.success('订单已导出PDF');
//       break;
//     case 'email':
//       ElMessage.success('订单已发送至邮箱');
//       break;
//   }
// };

// 查看关联单据
const viewRelatedDoc = (doc: RelatedDocument) => {
  if (doc.url) {
    router.push(doc.url);
  }
};

// 获取状态对应的标签类型
const getStatusType = (status: string) => {
  if (!status) return 'info';

  switch (status) {
    case '待收货':
      return 'info';
    case '已收货':
      return 'success';
    case '已开票':
      return 'warning';
    case '已取消':
      return 'danger';
    default:
      return 'info'; // 默认使用info类型，避免空值错误
  }
};

// 日期格式化
const formatDate = (dateStr: string) => {
  if (!dateStr) return '-';
  try {
    const date = new Date(dateStr);
    return date.toLocaleDateString('zh-CN');
  } catch (e) {
    return dateStr;
  }
};

// 日期时间格式化
const formatDateTime = (dateTimeStr: string) => {
  if (!dateTimeStr) return '-';
  try {
    const date = new Date(dateTimeStr);
    return date.toLocaleString('zh-CN');
  } catch (e) {
    return dateTimeStr;
  }
};

// 格式化货币
const formatCurrency = (value: number) => {
  if (!value && value !== 0) return '¥ 0.00';
  return `¥ ${Number(value).toFixed(2)}`;
};
</script>

<style scoped>
.order-detail-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-title {
  margin: 0;
  font-size: 20px;
  font-weight: 500;
}

.detail-card {
  margin-bottom: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  border-radius: 6px;
}

.section-title {
  font-size: 16px;
  font-weight: 500;
  margin: 30px 0 16px;
  padding-left: 10px;
  border-left: 3px solid #409EFF;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.title-text {
  color: #303133;
}

.goods-count {
  font-size: 13px;
  color: #909399;
  font-weight: normal;
}

.related-docs {
  margin-bottom: 20px;
}

.amount-summary {
  display: flex;
  justify-content: flex-end;
  margin-top: 24px;
  font-size: 16px;
  padding: 10px 20px;
  background-color: #f8f8f8;
  border-radius: 4px;
}

.amount-summary .label {
  font-weight: bold;
  margin-right: 10px;
}

.amount-summary .value {
  color: #f56c6c;
  font-weight: bold;
  font-size: 18px;
}

.amount-text {
  color: #f56c6c;
  font-weight: 500;
}

:deep(.el-descriptions__label) {
  width: 120px;
  text-align: right;
}

:deep(.el-descriptions__cell) {
  padding: 12px;
}

:deep(.el-descriptions__header) {
  margin-bottom: 10px;
  padding-left: 10px;
  border-left: 3px solid #409EFF;
}
</style> 